#include "data_view.h"
#include "ui_data_view.h"
#include "dealer_handler.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
#include <QFile>
#include <QDir>
#include <QMessageBox>
#include <QFileDialog>
#include "search_tree_widget.h"
#include "database_manager.h"

DataView::DataView(SearchTreeWidget *search_tree, QWidget *parent)
    : QWidget(parent),
      ui_(new Ui::DataView),
      search_tree_(search_tree),
      current_state_info_(new StateInfo),
      pagination_(100) // 每页100条数据
{
    ui_->setupUi(this);

    // 替换原有的树形控件
    QVBoxLayout *layout = new QVBoxLayout(ui_->leftContainer);
    layout->setContentsMargins(0, 0, 0, 0);

    // 设置表格列宽
    ui_->resultTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    ui_->resultTable->horizontalHeader()->setStretchLastSection(true);

    // 设置各列宽度
    ui_->resultTable->setColumnWidth(0, 60);     // 序号
    ui_->resultTable->setColumnWidth(1, 200);    // 时间
    ui_->resultTable->setColumnWidth(2, 120);    // 源地址
    ui_->resultTable->setColumnWidth(3, 120);    // 目的地址
    ui_->resultTable->setColumnWidth(4, 80);     // 报文方向
    ui_->resultTable->setColumnWidth(5, 80);     // 类型标识TI
    ui_->resultTable->setColumnWidth(6, 80);     // 传输原因COT
    ui_->resultTable->setColumnWidth(7, 80);     // 数据点名
    ui_->resultTable->setColumnWidth(8, 80);     // 数据点号
    ui_->resultTable->setColumnWidth(9, 80);     // 目标值
    ui_->resultTable->setColumnWidth(10, 100);   // 四遥类型
    ui_->resultTable->setColumnWidth(11, 120);   // 数据平面
    ui_->resultTable->setColumnHidden(12, true); // id

    // 连接搜索按钮的点击信号到槽函数
    connect(ui_->searchButton, &QPushButton::clicked,
            this, &DataView::onSearchButtonClicked);

    connect(ui_->generateReportButton, &QPushButton::clicked,
            this, &DataView::onGenerateReportButtonClicked);

    dealer_handler_ = DealerHandler::getInstance();
    // 连接网络消息信号到槽函数
    connect(dealer_handler_, &DealerHandler::messageReceived, this, &DataView::onNetworkMessageReceived);

    // 连接搜索树形控件项点击信号到槽函数
    connect(search_tree_, &SearchTreeWidget::itemClicked, this, &DataView::onSearchTreeWidgetItemClicked);

    // 连接分页按钮的点击信号到槽函数
    connect(ui_->prevPageButton, &QPushButton::clicked, this, &DataView::onPrevPageButtonClicked);
    connect(ui_->nextPageButton, &QPushButton::clicked, this, &DataView::onNextPageButtonClicked);

    // 连接报文方向复选框的信号到槽函数
    connect(ui_->upstreamCheckBox, &QCheckBox::stateChanged, this, &DataView::onDirectionFilterChanged);
    connect(ui_->downstreamCheckBox, &QCheckBox::stateChanged, this, &DataView::onDirectionFilterChanged);

    // 初始化分页UI
    updatePaginationUI();

    // 初始化点表下拉框
    initPointComboBox();
}

DataView::~DataView()
{
    if(current_state_info_)
    {
        delete current_state_info_;
    }
    delete ui_;
}

void DataView::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);

    // 设置搜索树形控件
    search_tree_->selectRootNode();
    search_tree_->setContextMenuEnabled(false);
    search_tree_->setShortcutEnabled(false);
    search_tree_->setDoubleClickEnabled(false);
    ui_->leftContainer->layout()->addWidget(search_tree_);

    // 设置时间控件的初始值
    QDateTime currentTime = QDateTime::currentDateTime();

    ui_->startTimeEdit->setDisplayFormat("yyyy-MM-dd HH:mm");
    ui_->startTimeEdit->setDateTime(currentTime);
    ui_->endTimeEdit->setDisplayFormat("yyyy-MM-dd HH:mm");
    ui_->endTimeEdit->setDateTime(currentTime.addSecs(1 * 3600)); // 默认查询1小时
    if(current_state_info_->id() != 0)
    {
        search_tree_->selectNodeByStateInfo(current_state_info_);
    }
}

void DataView::onSearchButtonClicked()
{
    QString jsonString = generateSelectPointInfoBody();
    dealer_handler_->sendRequest("select-point-info", jsonString);
}

void DataView::onNetworkMessageReceived(const QString &method, const QString &body)
{
    if (method == "select-point-info")
    {
        QJsonDocument doc = QJsonDocument::fromJson(body.toUtf8());
        if (!doc.isObject())
        {
            qDebug() << "Invalid JSON format: not an object";
            return;
        }

        QJsonObject obj = doc.object();
        QJsonArray data = obj["data"].toArray();
        int total = obj["total"].toInt();

        // 更新分页信息
        pagination_.setTotalCount(total);

        // 清空当前结果
        select_frames_result_.clear();

        // 遍历数组中的每个对象
        for (int i = 0; i < data.size(); i++)
        {
            QJsonObject item = data[i].toObject();
            SelectFramesResult result;
            // 生成result
            result.id = item["id"].toVariant().toLongLong();
            result.pointAddress = item["pointAddress"].toInt();
            result.pointValue = item["pointValue"].toDouble();
            result.pointType = item["pointType"].toInt();
            switch (result.pointType)
            {
            case 0:
                result.pointTypeDesc = "遥信";
                break;
            case 1:
                result.pointTypeDesc = "遥测";
                break;
            case 2:
                result.pointTypeDesc = "电度";
                break;
            case 3:
                result.pointTypeDesc = "遥控";
                break;
            case 4:
                result.pointTypeDesc = "遥调";
                break;
            case 5:
                result.pointTypeDesc = "SOE";
                break;
            default:
                result.pointTypeDesc = "未知";
                break;
            }
            result.pointDesc = item["pointDesc"].toString();
            result.tieIdentification = item["tieIdentification"].toInt();
            result.cause = item["cause"].toInt();
            result.tieIdentificationDesc = item["tieIdentificationDesc"].toString();
            result.causeDesc = item["causeDesc"].toString();
            result.srcHost = item["srcHost"].toString();
            result.srcName = item["srcName"].toString();
            result.dstHost = item["dstHost"].toString();
            result.dstName = item["dstName"].toString();
            result.direction = item["direction"].toString();
            result.directionDesc = result.direction == "Upstream" ? "上行" : "下行";
            result.dataPlane = item["dataPlane"].toString();
            result.timestamp = item["timestamp"].toVariant().toLongLong();
            result.timestampStr = QDateTime::fromMSecsSinceEpoch(result.timestamp).toString("yyyy-MM-dd HH:mm:ss.zzz");

            select_frames_result_.append(result);
        }
        pagination_.setCurrentPageData(select_frames_result_);

        // 更新表格数据
        updateDataTable();

        // 更新分页UI
        updatePaginationUI();
    }
    if (method == "generate-report")
    {
        QString filePath = QFileDialog::getSaveFileName(this,tr("导出报告"),QDir::homePath() + "/调试报告.docx",tr("文本文件 (*.docx);;所有文件 (*.*)"));
        if (filePath.isEmpty()) {
            return;
        }

        QFile file(filePath);
        if (!file.open(QIODevice::WriteOnly)) {
            QMessageBox::warning(this, tr("导出失败"), tr("无法打开文件进行写入: %1").arg(file.errorString()));
            return;
        }
        // 将base64字符串转换为二进制数据
        QByteArray fileData = QByteArray::fromBase64(body.toUtf8());
        file.write(fileData);
        file.close();
        // 显示成功提示
        QMessageBox::information(this, "提示", "报告已生成");
    }
}

void DataView::onGenerateReportButtonClicked()
{
    QString jsonString = generateSelectPointInfoBody();
    dealer_handler_->sendRequest("generate-report", jsonString);
}

void DataView::onSearchTreeWidgetItemClicked(StateInfo state_info)
{
    current_state_info_->setId(state_info.id());
    current_state_info_->setParentId(state_info.parentId());
    current_state_info_->setStateName(state_info.stateName());
    current_state_info_->setDescription(state_info.description());
    current_state_info_->setHost(state_info.host());
    current_state_info_->setPort(state_info.port());
    current_state_info_->setIsRtu(state_info.isRtu());
    // 更新点表下拉框
    initPointComboBox();
}

void DataView::onPrevPageButtonClicked()
{
    if (pagination_.hasPreviousPage())
    {
        pagination_.previousPage();
        onSearchButtonClicked();
    }
}

void DataView::onNextPageButtonClicked()
{
    if (pagination_.hasNextPage())
    {
        pagination_.nextPage();
        onSearchButtonClicked();
    }
}

void DataView::updatePaginationUI()
{
    // 更新页码显示
    ui_->pageLabel->setText(QString("第 %1 页").arg(pagination_.currentPage()));

    // 更新总记录数显示
    ui_->totalLabel->setText(QString("共 %1 条").arg(pagination_.totalCount()));

    // 更新按钮状态
    ui_->prevPageButton->setEnabled(pagination_.hasPreviousPage());
    ui_->nextPageButton->setEnabled(pagination_.hasNextPage());
}

QString DataView::generateSelectPointInfoBody()
{
    SelectFramesParams params;
    // 如果当前变电站是RTU，则设置源主机和目的主机
    if (current_state_info_ && current_state_info_->isRtu())
    {
        params.srcHost = current_state_info_->host();
        params.dstHost = current_state_info_->host();
    }
    else
    {
        params.srcHost = "";
        params.dstHost = "";
    }

    // 设置查询起止时间
    params.startTime = ui_->startTimeEdit->dateTime().toMSecsSinceEpoch();
    params.endTime = ui_->endTimeEdit->dateTime().toMSecsSinceEpoch();

    // 设置分页条件
    params.limit = pagination_.pageSize();
    params.offset = pagination_.offset();

    // 设置点号
    params.pointAddress = -1;
    if (ui_->pointComboBox->isEnabled())
    {
        params.pointAddress = ui_->pointComboBox->currentData().toLongLong();
    }

    // 序列化JSON
    QJsonObject jsonObject;
    jsonObject["srcHost"] = params.srcHost;
    jsonObject["dstHost"] = params.dstHost;
    jsonObject["startTime"] = QString::number(params.startTime);
    jsonObject["endTime"] = QString::number(params.endTime);
    jsonObject["limit"] = params.limit;
    jsonObject["offset"] = params.offset;
    jsonObject["pointAddress"] = params.pointAddress;
    QJsonDocument doc(jsonObject);
    return doc.toJson(QJsonDocument::Compact);
}

void DataView::updateDataTable()
{
    // 获取当前页数据
    QVector<SelectFramesResult> currentPageData = pagination_.getCurrentPageData();

    // 根据方向过滤条件过滤数据
    currentPageData = filterByDirection(currentPageData);

    // 清空表格
    ui_->resultTable->setRowCount(0);

    // 设置行数
    ui_->resultTable->setRowCount(currentPageData.size());

    // 遍历数据并填充表格
    for (int i = 0; i < currentPageData.size(); i++)
    {
        const SelectFramesResult &result = currentPageData[i];

        // 序号
        QTableWidgetItem *indexItem = new QTableWidgetItem(QString::number(i + 1));
        ui_->resultTable->setItem(i, 0, indexItem);

        // 时间
        QTableWidgetItem *timeItem = new QTableWidgetItem(result.timestampStr);
        ui_->resultTable->setItem(i, 1, timeItem);

        // 源地址
        QTableWidgetItem *srcItem = new QTableWidgetItem(result.srcName);
        ui_->resultTable->setItem(i, 2, srcItem);

        // 目的地址
        QTableWidgetItem *dstItem = new QTableWidgetItem(result.dstName);
        ui_->resultTable->setItem(i, 3, dstItem);

        // 报文方向
        QTableWidgetItem *directionItem = new QTableWidgetItem(result.directionDesc);
        ui_->resultTable->setItem(i, 4, directionItem);

        // 类型标识TI
        QTableWidgetItem *tiItem = new QTableWidgetItem(result.tieIdentificationDesc);
        ui_->resultTable->setItem(i, 5, tiItem);

        // 传输原因COT
        QTableWidgetItem *cotItem = new QTableWidgetItem(result.causeDesc);
        ui_->resultTable->setItem(i, 6, cotItem);

        // 数据点名
        QTableWidgetItem *pointNameItem = new QTableWidgetItem(result.pointDesc);
        ui_->resultTable->setItem(i, 7, pointNameItem);

        // 数据点号
        QTableWidgetItem *pointAddressItem = new QTableWidgetItem(QString::number(result.pointAddress));
        ui_->resultTable->setItem(i, 8, pointAddressItem);

        // 目标值
        QTableWidgetItem *valueItem = new QTableWidgetItem(QString::number(result.pointValue));
        ui_->resultTable->setItem(i, 9, valueItem);

        // 四遥类型
        QTableWidgetItem *typeItem = new QTableWidgetItem(result.pointTypeDesc);
        ui_->resultTable->setItem(i, 10, typeItem);

        // 数据平面
        QTableWidgetItem *planeItem = new QTableWidgetItem(result.dataPlane);
        ui_->resultTable->setItem(i, 11, planeItem);

        // id
        QTableWidgetItem *idItem = new QTableWidgetItem(QString::number(result.id));
        ui_->resultTable->setItem(i, 12, idItem);
    }
    // 设置表格列宽
    ui_->resultTable->resizeColumnToContents(5);
    ui_->resultTable->resizeColumnToContents(6);
    ui_->resultTable->resizeColumnToContents(7);
}

void DataView::onDirectionFilterChanged()
{
    // 当方向过滤条件改变时，直接更新表格显示
    updateDataTable();
}

QVector<SelectFramesResult> DataView::filterByDirection(const QVector<SelectFramesResult> &data)
{
    QVector<SelectFramesResult> filteredData;
    bool showUpstream = ui_->upstreamCheckBox->isChecked();
    bool showDownstream = ui_->downstreamCheckBox->isChecked();

    for (const auto &item : data)
    {
        if ((showUpstream && item.direction == "Upstream") ||
            (showDownstream && item.direction == "Downstream"))
        {
            filteredData.append(item);
        }
    }

    return filteredData;
}

void DataView::initPointComboBox()
{
    if (!current_state_info_)
    {
        return;
    }

    if (!current_state_info_->isRtu())
    {
        ui_->pointComboBox->setEnabled(false);
        return;
    }

    ui_->pointComboBox->setEnabled(true);

    // 清空下拉框
    ui_->pointComboBox->clear();
    ui_->pointComboBox->addItem("", -1);

    // 获取遥控点表信息
    QVector<PointInfo> ykpoints = DatabaseManager::queryPoints(current_state_info_->id(), static_cast<int>(PointInfo::Type::YK));

    // 获取遥调点表信息
    QVector<PointInfo> ytPoints = DatabaseManager::queryPoints(current_state_info_->id(), static_cast<int>(PointInfo::Type::YT));

    // 添加点表选项
    for (const auto &point : ykpoints)
    {
        ui_->pointComboBox->addItem(point.point_desc, point.point_id);
    }
    for (const auto &point : ytPoints)
    {
        ui_->pointComboBox->addItem(point.point_desc, point.point_id);
    }
}
